var express = require("express");
var router = express.Router();
let { user } = require("../models/model");
var jwt = require("jsonwebtoken");
const crypto = require("crypto");
function md5Password(password) {
  const md5 = crypto.createHash("md5");
  return md5.update(password).digest("hex");
}

router.delete("/del", async (req, res) => {
  await user.deleteOne({ _id: req.query._id });
  res.send({
    code: 200,
  });
});

router.get("/", async (req, res) => {
  let data = await user.find();
  res.send({
    code: 200,
    data,
  });
});
//用户注册
router.post("/zhuc", async (req, res) => {
  const { username, password, phone } = req.body;
  let un = await user.findOne({ username });
  if (un) {
    res.send({
      code: 404,
      msg: "姓名已存在",
    });
    return false;
  }
  let ph = await user.findOne({ phone });
  if (ph) {
    res.send({
      code: 404,
      msg: "手机号已存在",
    });
    return false;
  }
  await user.create({
    username,
    password: md5Password(password),
    phone,
  });
  res.send({
    code: 200,
  });
});
//用户账号密码登入

router.post("/loginpass", async (req, res) => {
  const { tel1, password } = req.body;
  const user1 = await user.findOne({
    phone: tel1,
    password: md5Password(password),
  });
  if (user1) {
    let token = jwt.sign({ phone: tel1 }, "2401a", { expiresIn: "1h" });
    res.send({
      code: 200,
      token,
      user1,
    });
  } else {
    res.send({
      code: 401,
      msg: "用户名或密码错误",
    });
  }
});
//手机号验证码登入

router.post("/loginyan", async (req, res) => {
  const phone = req.query.phone;
  const user1 = await user.findOne({ phone });
  if (user1) {
    let token = jwt.sign({ phone: phone }, "2401a", { expiresIn: "1h" });
    res.send({
      code: 200,
      token,
      user1,
    });
  } else {
    res.send({
      code: 401,
      msg: "用户名或密码错误",
    });
  }
});
//实名认证
router.post("/shiming", async (req, res) => {
  await user.updateOne({ _id: req.query._id }, { face_id: req.query.face_id });
  res.send({
    code: 200,
  });
});

//人脸登入返回token
router.post("/loginface", async (req, res) => {
  const face_id = req.query.face_id;
  const user1 = await user.findOne({ face_id });
  if (user1) {
    let token = jwt.sign({ face_id: face_id }, "2401a", { expiresIn: "1h" });
    res.send({
      code: 200,
      token,
      user1,
    });
  } else {
    res.send({
      code: 401,
      msg: "用户名或密码错误",
    });
  }
});

//腾讯人脸识别
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
const SMSClient = require("@alicloud/sms-sdk");
//人脸识别登录
router.post("/faceLogin", async (req, res) => {
  //获取前端传来的 base64
  let b64 = req.body.b64;
  const IaiClient = tencentcloud.iai.v20200303.Client;
  const clientConfig = {
    credential: {
      //自己的腾讯 secretId
      secretId: "AKIDRkxynRr5zkHYcXHn6CAGLXcTFUehdP5c",
      //自己的腾讯密匙
      secretKey: "VuDLG4hBbwMwTyOp9NdliXHsGQZZ4e9W",
    },
    region: "ap-beijing", //地域参数（华北地区北京）
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };
  const client = new IaiClient(clientConfig);
  const params = {
    GroupIds: [
      //你创建的人员库 ID
      "123456",
    ],
    Image: b64, //图片的 base64 格式编码
    NeedPersonInfo: 1, //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
    QualityControl: 0, //图片质量控制。 0: 不进行控制； 1:较低的质量要求
    FaceMatchThreshold: 85, //人脸对比度设置为大于 85 才可
  };
  let doc = await client.SearchFaces(params);
  // doc 为人脸识别后的返回信息
  console.log(doc, "doc");
  if (doc.Results[0].Candidates.length != 0) {
    //表示当前人脸库有该人员
    let personName = doc.Results[0].Candidates[0].PersonName; //拿到该人员的名称
    console.log(personName, "personNume");
    //生成 token
    let token = jwt.sign({ name: personName }, "face", { expiresIn: "1d" });
    res.send({
      code: 200,
      msg: "登录成功！",
      token,
      doc,
    });
  } else {
    res.send({
      code: 401,
      msg: "暂未入库",
    });
    return false;
  }
});

// addface 添加
router.post("/addface", async (req, res, next) => {
  let b64 = req.body.b64;
  let _id = req.body._id;
  console.log(_id);
  const IaiClient = tencentcloud.iai.v20200303.Client;

  const clientConfig = {
    credential: {
      secretId: "AKIDRkxynRr5zkHYcXHn6CAGLXcTFUehdP5c",
      secretKey: "VuDLG4hBbwMwTyOp9NdliXHsGQZZ4e9W",
    },
    region: "ap-beijing",
    profile: {
      endpoint: "iai.tencentcloudapi.com",
    },
  };

  function generateFourDigitRandomNumber() {
    return Math.floor(Math.random() * 9000) + 1000; // 生成 1000 到 9999 之间的随机数
  }
  let ccc = generateFourDigitRandomNumber() + "c";
  let bbb = generateFourDigitRandomNumber() + "b";
  // 实例化要请求产品的 client 对象,clientProfile 是可选的
  const client = new IaiClient(clientConfig);
  const params = {
    GroupId: "123456",
    PersonName: ccc,
    PersonId: bbb,
    Image: b64,
  };
  client.CreatePerson(params).then(
    (data) => {
      res.send({
        code: 200,
        msg: "添加成功",
        ccc,
        bbb,
      });
    },
    (err) => {
      console.log("error", err);
    }
  );
});

// 阿里云短信的信息配置
const accessKeyId = "LTAI5tPLouaEbHiQr8oyn3xZ";
const secretAccessKey = "8QTyEDyhNkMG4SBbvW6MDXNMfscoff";
const client = new SMSClient({ accessKeyId, secretAccessKey });

// 生成随机验证码
const getCode = () => Math.floor(100000 + Math.random() * 900000).toString();

// verifyCode接口，用于发送短信验证码
router.get("/verifyCode", (req, res) => {
  const phone = req.query.tel;
  console.log(phone);

  const code = getCode();
  client
    .sendSMS({
      PhoneNumbers: phone,
      SignName: "2401a班jxy",
      TemplateCode: "SMS_305528884",
      TemplateParam: JSON.stringify({ code }),
    })
    .then((response) => {
      const { Code } = response;
      console.log("-------", Code);
      if (Code === "OK") {
        // 如果发送成功，将验证码以字符串形式返回给前端
        res.send(JSON.stringify(code));
      } else {
        res
          .status(500)
          .json({ message: `Failed to send verification code: ${Code}` });
      }
    })
    .catch((err) => {
      console.log(err);
      res.status(500).json({ message: "Failed to send verification code" });
    });
});
module.exports = router;
